Nginx Virtual Hosts: Deploying Multiple Websites on a Single Server

This article introduces the Nginx virtual host feature, which allows a single server to host multiple websites, thereby reducing costs. The core is to simulate multiple virtual servers through technology. There are three implementation methods in Nginx: domain name-based (the most common, where different domains correspond to different websites), port-based (distinguished by different ports, suitable for scenarios without additional domains), and IP-based (for servers with multiple IPs, where different IPs correspond to different websites). Before configuration, Nginx needs to be installed, website content prepared (e.g., directories `/var/www/site1` and `/var/www/site2` with homepages), and domain name resolution or test domains (optional) should be ensured. Taking the domain name-based method as an example, the steps are: create the configuration file `/etc/nginx/sites-available/site1.com`, write a `server` block (listening on port 80, matching the domain name, specifying the root directory), configure the second website similarly, create a soft link to `sites-enabled`, test with `nginx -t`, and restart Nginx. For other methods: the port-based method requires specifying a different port (e.g., 8080) in the `server` block; the IP-based method requires the server to bind multiple IPs, with the `listen` directive in the configuration file specifying the IP and port. Common issues include permissions, configuration errors, and domain name resolution, which require checking directory permissions, syntax, and confirming that the domain name points to the server's IP. In summary, Nginx's virtual host feature is a cost-effective solution for hosting multiple websites on a single server, with flexible configuration options based on domain names, ports, or IPs to meet various deployment needs.

Read More
Detailed Explanation of Nginx Configuration Files: Server Block and Location for Beginners

The core of Nginx configuration lies in Server blocks (virtual hosts) and location blocks (path distribution). The main configuration file (nginx.conf) includes the global context (with directives like worker_processes), the events context (with worker_connections), and the http context (which contains multiple Server blocks). A Server block defines a website using directives such as listen (port), server_name (domain name), root (root directory), and index (homepage). Location blocks match requests based on paths, supporting prefix, exact, regular expression, and other types, with priority order: exact match > prefix with ^~ > ordinary prefix > regular expression > default. After configuration, use `nginx -t` to verify syntax and `nginx -s reload` to apply changes. After mastering basic configurations (port, domain name, static path), beginners can progressively learn advanced features like dynamic request forwarding and caching.

Read More